var express = require("express");
var router = express.Router();
const db = require("../db/index");
const multer = require('multer')
// 用这个包来生成 Token 字符串
const jwt = require("jsonwebtoken");
// 导入配置文件
const config = require("../config");
const { query } = require("express");
// 登录
router.post("/login", function (req, res, next) {
  const info = req.body;
  console.log("info", info);
  if (!info.username || !info.password) {
    return res.send({ message: "用户名或密码不能为空！" });
  }
  const sql = `select * from ${info.role} where username=?`;
  db.query(sql, info.username, function (err, results) {
    if (err) {return res.send({message:err.message});}
    if(results.length == 0) {return res.send({message:'用户名不存在'});}
    if (results[0].password !== info.password)
    { return res.send({ message: "密码错误，请重新输入！" });}else{
      const user = {
        ...results[0],
        password: "",
        nickname: "",
        username: "",
        phone: "",
        photo: "",
        date: "",
      };
      const tokenStr = jwt.sign(user, config.jwtSecretKey, {
        expiresIn: "1000h",
      });
     return  res.send({ code: 200, message: "登陆成功", token: tokenStr });
    }
      
   
  });
});
// 退出
router.post("/logout", function (req, res, next) {
  let token = req.headers.token;
  console.log(token);
  jwt.verify(token, config.jwtSecretKey, function (err, data) {
    if (data) {
      return res.send({ code: 200, message: "退出成功" });
    } else {
      return res.send({ code: 0, message: "token无效" });
    }
  });
});
// 获取信息

router.get("/getInfo", function (req, res, next) {
  let token = req.headers.token;
  jwt.verify(token, config.jwtSecretKey, function (err, result) {
    if (err) res, send({ message: err.message });
    if (result) {
      const sql = `select * from ${result.role} where id=?`;
      db.query(sql, result.id, function (err, results) {
        if (err) res, send({ message: err.message });
        console.log(results);
        res.send({ code: 200, message: "获取成功", data: results[0] });
      });
    }
  });
});

// 修改用户信息

router.post("/updateInfo", function (req, res, next) {
  let info = req.body;

  const sql = `update ${info.role} set username=?,nickname=?,phone=?,date=?,photo=? where id=? `;
  db.query(
    sql,
    [info.username, info.nickname, info.phone, info.date, info.photo, info.id],
    function (err, results) {
      if (err) res.send({ code: 0, message: err.message });
      res.send({ code: 200, data: info, message: "修改成功" });
    }
  );
});

// 修改用户密码
router.post("/updatePwd", function (req, res, next) {
  let token = req.headers.token
  let info = req.body;
  jwt.verify(token, config.jwtSecretKey, function (err, result) {
    if (err){return res.send({ message: err.message }); } 
    console.log(result);
    const sql = `update ${result.role} set password=? where id=?`;
    db.query(sql, [info.newValue, result.id], (err, results) => {
      if (err) {return res.send({ message: err.message });} 
      res.send({ code: 200, message: "修改成功" });
    });
  });
});

// 上传图片
const upload = multer({dest:__dirname+'/../uploads'})
router.post("/upload",upload.single('file'), function (req, res, next) {
  res.header("Access-Control-Allow-Origin","*");
  const file =req.file
  file.url =`http://127.0.0.1:3000/uploads/${file.filename}`
  console.log(file.url.split('/')[3]);
  res.send(file.url)
 
});



module.exports = router;
